//
//  NetAPIManager.m
//  dongbo
//
//  Created by 葛殿宏 on 16/2/22.
//  Copyright © 2016年 arenacloud. All rights reserved.
//

#import "NetAPIManager.h"
#import "NetAPIClient.h"
#import "UserManager.h"

#define payAppId   @"1000003"
#define payAppKey  @"f31c147335274c56d801f833d3c26a70"

@implementation NetAPIManager

+ (instancetype)sharedManager {
    static NetAPIManager *shared_manager = nil;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        shared_manager = [[self alloc] init];
    });
    return shared_manager;
}

- (void)request_LoginWithUsername:(NSString *)username password:(NSString *)password WithBlock:(void (^)(id data, NSError *error))block{
    
    [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:@"app/1/-/login.api" withParams:@{@"username":username,@"password":password} withMethodType:Post autoShowError:YES andBlock:^(id data, NSError *error) {
        block(data, error);
    }];
}

- (void)request_RoomlistWithBlock:(void (^)(id data, NSError *error))block{
    
    if (![CommonUtil isEmptyString:[UserManager shareInstance].user.accountId]) {
        NSString *roomlistUrl = [NSString stringWithFormat:@"/1/-/rooms?accountId=%@",[UserManager shareInstance].user.accountId];
        [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:roomlistUrl withParams:nil withMethodType:Get autoShowError:YES andBlock:^(id data, NSError *error) {
            block(data, error);
        }];
    }
}

- (void)request_CreateWithRoomname:(NSString *)name password:(NSString *)password ticket:(NSString *)ticket cover:(NSString *)coverUrl roomId:(NSString *)roomId isCreate:(BOOL)isCreate WithBlock:(void (^)(id data, NSError *error))block{
    
    NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] init];
    [aDictionary setValue:name forKey:@"name"];
    if (![CommonUtil isEmptyString:password]) {
        [aDictionary setValue:password forKey:@"password"];
    }
    else
    {
        [aDictionary setValue:@"" forKey:@"password"];
    }
    
    if (![CommonUtil isEmptyString:ticket]) {
        [aDictionary setValue:ticket forKey:@"amount"];
    }
    else
    {
        [aDictionary setValue:@"0" forKey:@"amount"];
    }

    [aDictionary setValue:[[UserManager shareInstance].user.accountId stringValue] forKey:@"accountId"];

    if (![CommonUtil isEmptyString:password]) {
        [aDictionary setValue:@(1) forKey:@"wechType"];
    }
    else if (![CommonUtil isEmptyString:ticket])
    {
        [aDictionary setValue:@(2) forKey:@"wechType"];
    }
    else
    {
        [aDictionary setValue:@(0) forKey:@"wechType"];
    }
    
    if (coverUrl) {
        [aDictionary setValue:coverUrl forKey:@"cover"];
    }
    if (roomId) {
        [aDictionary setValue:roomId forKey:@"id"];
    }
    
    NSString *url = @"/1/-/room";
    [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:url withParams:aDictionary withMethodType:(roomId?Put:Post) autoShowError:YES andBlock:^(id data, NSError *error) {
        block(data, error);
    }];
}

- (void)request_Pay:(NSString *)price WithBlock:(void (^)(id data, NSError *error))block
{
    NSString *url = nil;

    #ifdef DEBUG
        url = @"arenapay/api/pay";
    #else
        url = @"api/pay";
    #endif
    
    NSString *ipAddr = [CommonUtil getIPAddress];
    if ([ipAddr isEqualToString:@"error"] || [ipAddr isEqualToString:@"127.0.0.1"]) {
        ipAddr = @"192.168.11.200";
    }
    NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
    f.numberStyle = NSNumberFormatterDecimalStyle;
    NSNumber *priceNumber = [f numberFromString:price];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    NSMutableDictionary *aDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                        payAppId,@"appId",
                                        [UserManager shareInstance].user.accountId,@"uid",
                                        @"APP",@"clientType",
                                        [NSString stringWithFormat:@"arenacloud.dongbo%ld",(long)[[NSDate date] timeIntervalSince1970]*1000],@"outTradeNo",
                                        [[UIDevice currentDevice].identifierForVendor UUIDString],@"clientId",
                                        ipAddr,@"clientIp",
                                        timeSp,@"time",
                                        @"CashWallet",@"accountsType",
                                        @"WEIXINPAY",@"payMethod",
                                priceNumber,@"income",nil];
    
    NSMutableArray *list = [[NSMutableArray alloc] init];
    for (int i = 0; i < aDictionary.allKeys.count; i++)
    {
        [list addObject:[NSString stringWithFormat:@"%@=%@&", aDictionary.allKeys[i], aDictionary.allValues[i]]];
    }
    NSArray *sortedArray = [list sortedArrayUsingSelector:@selector(compare:)];
    NSMutableString *beforeSignStr = [[NSMutableString alloc] init];
    for (int i = 0; i < sortedArray.count; i++) {
        [beforeSignStr appendString:sortedArray[i]];
    }
    [beforeSignStr appendString:[NSString stringWithFormat:@"key=%@", payAppKey]];
    
    NSString *sign = [CommonUtil md5Encoding:beforeSignStr];
    [aDictionary setValue:sign forKey:@"sign"];
    
    [[NetAPIClient sharedPayClient] requestJsonDataWithPath:url withParams:aDictionary withMethodType:Post autoShowError:YES andBlock:^(id data, NSError *error) {
        block(data, error);
    }];
}

- (void)request_FeedBackWithContent:(NSString *)content phone:(NSString *)phone mail:(NSString *)mail WithBlock:(void (^)(id data, NSError *error))block
{
    NSMutableDictionary *aDictionary = [[NSMutableDictionary alloc] init];
    [aDictionary setValue:content forKey:@"content"];
    if (phone) {
        [aDictionary setValue:phone forKey:@"phone"];
    }
    if (mail) {
        [aDictionary setValue:mail forKey:@"mail"];
    }
    
    if (![CommonUtil isEmptyString:[UserManager shareInstance].user.accountId]) {
        NSString *feedbackUrl = [NSString stringWithFormat:@"1/-/feedback/%@",[UserManager shareInstance].user.accountId];
        [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:feedbackUrl withParams:aDictionary withMethodType:Post autoShowError:YES andBlock:^(id data, NSError *error) {
            block(data, error);
        }];
    }
}

-(void)request_uploadImage:(UIImage *)image andBlock:(void (^)(id data, NSError *error))block
{
    NSString *uploadUrl = [NSString stringWithFormat:@"openAPI/1/-/uploadImg/%@",[UserManager shareInstance].user.accountId];

    NSDictionary *fileDic;
    if (image) {
        fileDic = @{@"image":image,@"name":@"file",@"fileName":@"icon.jpg"};
    }
    
    [[NetAPIClient sharedHttpClient] requestJsonDataWithPath:uploadUrl file:fileDic withParams:nil withMethodType:Post andBlock:^(id data, NSError *error) {
        if (data) {
            if ([data isKindOfClass:[NSDictionary class]]) {
                id resultData = [data valueForKeyPath:@"data"];
                block(resultData, nil);
            }
            else if ([data isKindOfClass:[NSData class]])
            {
                NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];
//                id resultData = [data valueForKeyPath:@"data"];
                block(result, nil);
            }
            
        }else{
            block(nil, error);
        }
    }];
}


/**
 * 根据流ID post 修改参数
 * <p/>
 * 通知后台流的打开或者关闭
 *
 * @param id      流ID
 * @param param   close/start
 * @param handler
 */
//public void openOrCloseStream(String id, String param, final StreamResponseHandler handler) {
//    String url = BASE_URL + "/broadcast/" + id;
//    
//    RequestParams rq = new RequestParams();
//    rq.add("a", param);
//    mClient.post(url, rq, new AsyncHttpResponseHandler() {
//        @Override
//        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
//            log.i("--statusCode= " + statusCode + "response = " + new String(response));
//            handler.onSuccess(new Stream(new JSONObject()));
//        }
//        
//        @Override
//        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
//            log.e("openOrCloseStream---->onFailure i = " + i + ",throwable.getMessage() = " + throwable.getMessage());
//            handler.onFailure(throwable, i);
//        }
//        
//    });
//}

- (void)request_openOrCloseStreamWithId:(NSString *)roomid param:(NSString *)param WithBlock:(void (^)(id data, NSError *error))block{
    
    NSString *broadcastUrl = [NSString stringWithFormat:@"broadcast/%@?a=%@",roomid,param];

    [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:broadcastUrl withParams:nil withMethodType:Post autoShowError:YES andBlock:^(id data, NSError *error) {
        block(data, error);
    }];
}

- (void)request_ExpenseWithStreamId:(NSString *)streamId WithBlock:(void (^)(id data, NSError *error))block
{
    NSString *expenseUrl = [NSString stringWithFormat:@"expense/%@",streamId];

    [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:expenseUrl withParams:nil withMethodType:Get autoShowError:YES andBlock:^(id data, NSError *error) {
        block(data, error);
    }];
}

- (void)request_MyInfoWithBlock:(void (^)(id data, NSError *error))block
{
    NSString *infoUrl = [NSString stringWithFormat:@"/1/-/my/%@",[UserManager shareInstance].user.accountId];
    
    [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:infoUrl withParams:nil withMethodType:Get autoShowError:YES andBlock:^(id data, NSError *error) {
        block(data, error);
    }];
}

- (void)request_deleteRoomWithId:(NSString *)roomid withBlock:(void (^)(id data, NSError *error))block{
    
    NSString *deleteRoomUrl = [NSString stringWithFormat:@"/1/-/room?id=%@&accountId=%@",roomid,[UserManager shareInstance].user.accountId];
    
    [[NetAPIClient sharedJsonClient] requestJsonDataWithPath:deleteRoomUrl withParams:nil withMethodType:Delete autoShowError:YES andBlock:^(id data, NSError *error) {
        block(data, error);
    }];
}

@end
